package com.central.apps.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.central.app.service.HandlerService;
import com.central.common.exception.service.ServiceException;
import com.central.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/update")
@Slf4j
public class StoreController {

    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";

    @Autowired
    private HandlerService handlerService;
    @PostMapping("/usestatus")
    public String generatePO(@RequestBody Map<String,Object> params) throws Exception {

        String id = MapUtils.getString(params,"id");
        String usestatus = MapUtils.getString(params,"usestatus");
        String upd = "update gq_store set usestatus='"+usestatus+"' where id = "+id;
        handlerService.updateBySql(upd);
        JSONObject json = new JSONObject();
        json.put("code", "0");
        json.put("msg", "使用状态修改成功");
        return json.toString();
    }

    /**
     * 库房-货位子表模板导出
     * @param response
     * @throws IOException
     */
    @PostMapping("/areashelfExportExcel")
    public void itemTypeExportExcel(HttpServletResponse response) throws IOException {
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("Sheet1");
            HSSFRow row = sheet.createRow(0);

            HSSFFont redFont = wb.createFont();
            redFont.setColor(Font.COLOR_RED);
            HSSFCellStyle style = wb.createCellStyle();
            style.setFont(redFont);
            style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.LEFT);// 左右居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中

            row.createCell(0).setCellValue("货架描述");
            HSSFCell cell1 = row.createCell(1);
            cell1.setCellStyle(style);
            cell1.setCellValue("货位描述*");
            HSSFCell cell2 = row.createCell(2);
            cell2.setCellStyle(style);
            cell2.setCellValue("货架编号*");
            HSSFCell cell3 = row.createCell(3);
            cell3.setCellStyle(style);
            cell3.setCellValue("层号*");
            HSSFCell cell4 = row.createCell(4);
            cell4.setCellStyle(style);
            cell4.setCellValue("位号*");
            row.createCell(5).setCellValue("备注");

            //输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
            String exportFileName ="库房货位信息.xls";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            response.setContentType("application/x-xls");
            wb.write(output);
            output.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 库房-货位子表模板导入
     * @param myfile
     * @throws Exception
     */
    @PostMapping("/areashelfImportExcel")
    @Transactional(rollbackFor = Exception.class)
    public Result inquiryImportExcel(@RequestParam("file") MultipartFile myfile, @RequestParam("id") String id) throws Exception {
        try {
            if(StringUtils.isBlank(id)){
                throw new ServiceException("未选择一条库房信息！");
            }

            Workbook workbook = null;
            String fileName = myfile.getOriginalFilename();
            if (fileName.endsWith(XLS)) {//获取文件后缀
                workbook = new HSSFWorkbook(myfile.getInputStream());
            } else if (fileName.endsWith(XLSX)) {
                workbook = new XSSFWorkbook(myfile.getInputStream());
            } else {
                throw new ServiceException("文件不是excel文件");
            }

            Sheet sheet1 = workbook.getSheet("Sheet1");
            int rows = sheet1.getLastRowNum();
            if (rows == 0) {
                throw new ServiceException("请填写数据");
            }

            List<Map<String, Object>> bySql = handlerService.findBySql("select storenum from gq_store where id = '" + id + "'");
            String storenum = MapUtils.getString(bySql.get(0), "storenum");

            List<Map<String, Object>> resultList = new ArrayList<>();
            for (int i = 0; i <= rows; i++) {
                //读取左上端单元格
                Row row = sheet1.getRow(i);
                //行不为空
                if (row != null) {
                    String rowdesc = getCellValue(row, 0).toString().trim();
                    String shelfdesc = getCellValue(row, 1).toString().trim();
                    String rownum = getCellValue(row, 2).toString().trim();
                    String storeynum = getCellValue(row, 3).toString().trim();
                    String tagnum = getCellValue(row, 4).toString().trim();
                    String note = getCellValue(row, 5).toString().trim();

                    if (i == 0) {
                        if(!"货位描述*".equals(shelfdesc) || !"货架编号*".equals(rownum) || !"层号*".equals(storeynum)
                            || !"货架描述".equals(rowdesc) || !"位号*".equals(tagnum) || !"备注".equals(note)){
                            throw new ServiceException("导入的模板错误，请下载模板进行导入");
                        }
                    }else{
                        //校验必填项
                        if(StringUtils.isBlank(shelfdesc) || StringUtils.isBlank(rownum) || StringUtils.isBlank(storeynum) || StringUtils.isBlank(tagnum)){
                            int line = i+1;
                            throw new ServiceException("第"+line+"行有必填字段未填写，填写后再进行导入！");
                        }

                        Map<String, Object> map = new HashMap<>();
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(storenum).append("-").append(rownum).append("-").append(storeynum).append("-").append(tagnum);
                        map.put("shelfnum",stringBuilder.toString());
                        map.put("shelfdesc",shelfdesc);
                        map.put("rownum",rownum);
                        map.put("storeynum",storeynum);
                        map.put("rowdesc",rowdesc);
                        map.put("tagnum",tagnum);
                        map.put("note",note);
                        map.put("storenum",storenum);
                        resultList.add(map);
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(resultList)){
                handlerService.batchInsert("storeApp","gq_areashelf",resultList);
            }
            return Result.succeed("成功导入"+resultList.size()+"条数据");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 获取Cell内容
     */
    public Object getCellValue(Row row, int column) {
        Object val = "";
        try {
            Cell cell = row.getCell(column);
            if (cell != null) {

                if (cell.getCellTypeEnum()==CellType.NUMERIC) {
                    val = cell.getNumericCellValue();
                    DecimalFormat df = new DecimalFormat("#.#########");
                    String cellValueStr = String.valueOf(val);
                    val = df.format(Double.valueOf(cellValueStr));
                } else if (cell.getCellTypeEnum() == CellType.STRING) {
                    val = cell.getStringCellValue();
                } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
                    val = cell.getCellFormula();
                } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
                    val = cell.getBooleanCellValue();
                } else if (cell.getCellTypeEnum() == CellType.ERROR) {
                    val = cell.getErrorCellValue();
                }
            }
        } catch (Exception e) {
            return val;
        }
        return val;
    }
}
